import 'package:flutter/material.dart';
import 'package:flutter_native_splash/flutter_native_splash.dart';
import 'package:get/get.dart';
import 'package:smart_ai_dart/extends/extensions.dart';
import 'package:smart_ai_dart/routers/app_pages.dart';
import 'package:smart_ai_dart/utils/common_utils.dart';
import 'package:smart_ai_dart/utils/database.dart';
import 'package:smart_ai_dart/utils/log_utils.dart';
import 'package:smart_ai_dart/utils/request.dart';
import 'package:smart_ai_dart/utils/storage.dart';
import 'package:smart_ai_dart/utils/themes.dart';
import 'package:smart_ai_dart/utils/translate.dart';
import 'package:media_kit/media_kit.dart';

void main() async {
  WidgetsBinding widgetsBinding = WidgetsFlutterBinding.ensureInitialized();
  // 保持启动页
  FlutterNativeSplash.preserve(widgetsBinding: widgetsBinding);
  // 初始化日志
  await LogUtils.shared.init();
  // 初始化媒体库
  MediaKit.ensureInitialized();
  // 初始化主题
  await AppTheme.shared.init();
  // 初始化翻译服务
  await TranslateService.init();
  // 初始化存储
  await StorageUtils.shared.init();
  // 初始化数据库
  await DatabaseUtils.shared.init();
  // 初始化网络请求
  await HttpUtils.shared.init(baseUrl: 'https://api.example.com');
  // 检查是否是第一次启动
  bool isFirstTime = await CommonUtils.checkFirstLaunch();
  if (isFirstTime == false) {
    FlutterNativeSplash.remove(); // 如果不是首次启动，立即移除启动页
  }

  LogUtils.shared.i('======= initilized app ======');
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    Color? color = '#000000'.toColor();
    color = ColorExtension.fromHex('#000000', opacity: 0.5);

    // 使用 ValueListenableBuilder 监听主题变化
    return ValueListenableBuilder<ThemeMode>(
      valueListenable: AppTheme.shared.themeNotifier,
      builder: (context, themeMode, child) {
        return GetMaterialApp(
          title: 'Flutter Demo',
          themeMode: themeMode,
          theme: AppTheme.shared.lightTheme,
          darkTheme: AppTheme.shared.darkTheme,
          getPages: AppPages.routes,
          initialRoute: AppPages.INITIAL,
          translations: TranslateService.instance, // 添加国际化支持
          locale: TranslateService.currentLocale, // 使用设备语言
          fallbackLocale: TranslateService.fallbackLocale, // 默认语言
        );
      },
    );
  }
}
